package freespiritsocial.io.user.ui.fragment.home

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.view.get
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MapStyleOptions
import com.google.android.libraries.places.api.model.Place
import com.scwang.smart.refresh.layout.util.SmartUtil.dp2px
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.data.model.PlaceItem
import freespiritsocial.io.user.databinding.FrgExploreBinding
import freespiritsocial.io.user.decoration.SpaceItemDecoration
import freespiritsocial.io.user.ext.init
import freespiritsocial.io.user.ext.loadListData
import freespiritsocial.io.user.ui.activity.MainAct
import freespiritsocial.io.user.ui.adapter.ExploreFilterAdapter
import freespiritsocial.io.user.ui.adapter.PostAdapter
import freespiritsocial.io.user.ui.helper.GoogleApiHelper
import freespiritsocial.io.user.ui.helper.MarkerHelper
import freespiritsocial.io.user.util.CacheUtil
import freespiritsocial.io.user.viewmodel.ExploreViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction

/**
 * @description 探索页
 */
class ExploreFrg: BaseFragment<ExploreViewModel,FrgExploreBinding>(),OnMapReadyCallback {
    companion object {
        var defLatLng = LatLng(51.51531377753747,-0.13387709484834562)
    }

    private val googleApiHelper by lazy(LazyThreadSafetyMode.NONE) {
        GoogleApiHelper(requireContext())
    }
    var mMap: GoogleMap? = null
    private val exploreFilterAdapter by lazy(LazyThreadSafetyMode.NONE) {
        ExploreFilterAdapter(mViewModel).apply {
            setOnItemClickListener { adapter,view,position ->
                if (mViewModel.tagName != this.data[position].tagName) {
                    mViewModel.tagName = this.data[position].tagName
                    emptyText?.text = "There are currently no posts."
                } else {
                    mViewModel.tagName = null
                    emptyText?.text = "No one has posted any posts yet."
                }
                adapter.notifyDataSetChanged()
            }
        }
    }
    private val postAdapter by lazy(LazyThreadSafetyMode.NONE) {
        PostAdapter().apply {
            setOnItemClickListener { _,_,position ->
                nav().navigateAction(R.id.explorePostDetailFrg,bundleOf("position" to position))
            }
        }
    }
    private val emptyText by lazy(LazyThreadSafetyMode.NONE) {
        postAdapter.emptyLayout?.get(0)?.findViewById<TextView>(R.id.empty_tv)
    }

    override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
        //设置view model作用域
        viewModelOwner = (activity as MainAct).exploreViewModelOwner
        super.onViewCreated(view,savedInstanceState)
    }

    override fun layoutId(): Int = R.layout.frg_explore

    @SuppressLint("ClickableViewAccessibility")
    override fun initView(savedInstanceState: Bundle?) = with(mDatabind) {
        click = Click()
        listPost.init(
            postAdapter,
            GridLayoutManager(requireContext(),2),
            emptyText = "No one has posted any posts yet.",
            emptyImage = R.mipmap.empty_posts_list,
            isScroll = false
        )
        listFilter.init(
            exploreFilterAdapter,
            LinearLayoutManager(requireContext(),RecyclerView.HORIZONTAL,false),
            hasEmpty = false
        ).addItemDecoration(SpaceItemDecoration(0,0,dp2px(13f)))
        cardMap.scrollView = scrollView
        mViewModel.getPostList(true)
        mViewModel.getTagList {
            exploreFilterAdapter.addData(it)
        }
    }

    override fun dismissLoading() {
        super.dismissLoading()
        mDatabind.refresh.finishRefresh()
        mDatabind.refresh.finishLoadMore()
    }

    override fun createObserver() {
        super.createObserver()
        lifecycleScope.launch {
            mViewModel.postResult.collect {
                loadListData(it,postAdapter,mDatabind.refresh)
            }
        }
        eventViewModel.savePostEvent.observe(this) {
            val postPojo = postAdapter.data.find { data -> data.invitationId == it } ?: return@observe
            postPojo.isSave = postPojo.isSave?.not()
            postAdapter.notifyItemChanged(postAdapter.data.indexOf(postPojo))
        }
        eventViewModel.hidePostEvent.observe(this) {
            postAdapter.data.find { data -> data.invitationId == it } ?: return@observe
//            postAdapter.remove(postPojo)
            mViewModel.getPostList(true)
        }
        eventViewModel.likePostEvent.observe(this) {
            val postPojo = postAdapter.data.find { data -> data.invitationId == it } ?: return@observe
            postPojo.isLike = postPojo.isLike?.not()
            postPojo.likeCount += if (postPojo.isLike == true) 1 else -1
            postAdapter.notifyItemChanged(postAdapter.data.indexOf(postPojo))
        }
        eventViewModel.delPostEvent.observe(this) {
            postAdapter.data.find { data -> data.invitationId == it } ?: return@observe
            mViewModel.getPostList(true)
        }
        appViewModel.locationPermission.observe(this) { hasPermission ->
            if (hasPermission.not()) return@observe
            googleApiHelper.findCurrentPlace {
                it ?: return@findCurrentPlace
                val toPlace = it.toPlace()
                CacheUtil.setCurPlace(toPlace)
                appViewModel.locationPlace.postValue(toPlace)
//                defLatLng = it.latLng
//                appViewModel.curLatLng.postValue(defLatLng)
            }
        }
        appViewModel.curLatLng.observe(this) {
            mMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(it,MarkerHelper.curZoom))
        }
    }

    override fun lazyLoadData() {
        loadMap()
    }

    private fun loadMap() {
        (childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment).getMapAsync(this)
    }

    override fun onDestroyView() {
        googleApiHelper.onDestroy()
        super.onDestroyView()
        viewModelOwner?.viewModelStore?.clear()
    }

    inner class Click {
        fun openMap() {
            nav().navigateAction(R.id.action_mainFrg_to_mapFrg)
        }

        fun onRefresh() {
            mViewModel.getPostList(true)
        }

        fun onLoadMore() {
            mViewModel.getPostList()
        }

    }

    override fun onMapReady(map: GoogleMap) {
        mMap = map
        mMap?.setMapStyle(MapStyleOptions.loadRawResourceStyle(requireContext(),R.raw.style_json))
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(defLatLng,MarkerHelper.curZoom))
        map.setOnCameraMoveListener {
            MarkerHelper.changeZoom(map.cameraPosition.zoom)
        }
        mViewModel.coordinate {
            MarkerHelper.parseData(it)
            MarkerHelper.parseMarker(mMap ?: return@coordinate)
        }
        map.setOnMapClickListener {
            appViewModel.curLatLng.postValue(mMap?.cameraPosition?.target)
            nav().navigateAction(R.id.action_mainFrg_to_mapFrg)
        }

        mMap?.setOnMarkerClickListener { marker ->
            return@setOnMarkerClickListener true
        }
    }

    fun Place.toPlace() = PlaceItem(latLng,address,id)

    fun resetMap() {
        MarkerHelper.parseMarker(mMap ?: return)
    }
}